package com.jeeplus.mob.web;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.mob.common.DataConvertHelper;
import com.jeeplus.mob.common.WxUtil;
import com.jeeplus.mob.service.UserInfoService;
import com.jeeplus.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "/mob/user")
@Api(tags = "用户登录")
public class UserInfoController {

    @Autowired
    private UserInfoService userService;

    /**
     * 首页登录
     * @param loginAccount：登录账号
     * @param password：密码
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.GET)
    @ApiOperation(value = "用户首页登录")
    public AjaxJson login(@RequestParam("userName") String loginAccount, @RequestParam("password") String password) {
        return userService.login(loginAccount, password);
    }

    /**
     * 修改密码
     * @param id
     * @param oldLoginAccount
     * @param newLoginAccount
     * @return
     */
    @RequestMapping(value = "updatePassword",method = RequestMethod.POST)
    @ApiOperation(value = "密码修改")
    public AjaxJson updatePassword(@RequestParam("userId") String id, @RequestParam("oldPassword") String oldLoginAccount,@RequestParam("newPasswrod") String newLoginAccount) {
        return userService.updateLoginAccount(id,oldLoginAccount,newLoginAccount);
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "logout",method = RequestMethod.GET)
    @ApiOperation(value = "退出登录")
    @Deprecated
    public AjaxJson logout(@RequestParam("userId") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        String token = UserUtils.getToken();
        if (StringUtils.isNoneBlank(token)) {
            UserUtils.clearCache();
            UserUtils.getSubject().logout();
        }
        ajaxJson.setMsg("退出成功！");
        return ajaxJson;
    }

    @ApiOperation(value = "公众号拉起微信授权")
    @GetMapping("wechatLogin")
    public void wechatLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        Map<String, Object> con = userInfoMapper.findCon();
        Map<String, Object> dataMap = DataConvertHelper.getRequestParams(request);
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        String backUrl = "http://localhost:8081/mapBackend/mob/login/callLoginBack.do";
        String scope = "snsapi_userinfo";
        // 微信公众平台
        String get_auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid="
                + "wxefca9546d0a32055" // wxappid
                + "&redirect_uri="
                + URLEncoder.encode(backUrl, "UTF-8")
                + "&response_type=code"
                + "&scope="
                + scope
                + "&state="
                + state
                + "#wechat_redirect";
        response.sendRedirect(get_auth_url);
    }

    @ApiOperation(value = "公众号授权回调获取用户信息")
    @GetMapping(value = "/callLoginBack.do")
    public void callLoginBack(HttpServletRequest requset, HttpServletResponse response) throws Exception {
        Map<String, Object> dataMap = DataConvertHelper.getRequestParams(requset);
        String code = requset.getParameter("code");
        String wx_appid = "wxefca9546d0a32055";
        String WX_APP_KEY = "6e09374526f44dc630674b05a9934149";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wx_appid + "&secret="
                + WX_APP_KEY + "&code=" + code + "&grant_type=authorization_code";
        net.sf.json.JSONObject authInfo = WxUtil.doGetStr(url);
        String access_token = authInfo.getString("access_token");
        String openid = authInfo.getString("openid");
        System.out.println("openId:" + openid);
        String refresh_token = authInfo.getString("refresh_token");
        String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
        net.sf.json.JSONObject chickuserinfo = WxUtil.doGetStr(chickUrl);
        if (!"0".equals(chickuserinfo.getString("errcode"))) {
            String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid
                    + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            net.sf.json.JSONObject refreshInfo = WxUtil.doGetStr(refreshTokenUrl);
            access_token = refreshInfo.getString("access_token");
        }
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                + "&lang=zh_CN";
        net.sf.json.JSONObject userInfoJson = WxUtil.doGetStr(userInfoUrl);
        /*UserInfo userInfo = new UserInfo();
        if (userInfoJson.containsKey("unionid")) {
            userInfo.setWxOpenid(userInfoJson.get("unionid").toString());
            userInfo.setImage(userInfoJson.get("headimgurl").toString());
            userInfo.setNikeName(userInfoJson.get("nickname").toString());
        }
        String json = JSONObject.toJSONString(userInfo);
        System.out.println(json);*/
        response.sendRedirect("http://localhost:8081/pigfull" + "pd/index.html?wxOpenid=" + userInfoJson.get("unionid").toString()
                + "&image=" + userInfoJson.get("headimgurl").toString()
                + "&nikeName=" + userInfoJson.get("nickname").toString());

    }

    @RequestMapping(value = "/getOpenId",method = RequestMethod.POST)
    public AjaxJson getOpenId(HttpServletRequest request,HttpServletResponse response) {
        Map<String, Object> requestParamsNoToken = DataConvertHelper.getRequestParamsNoToken(request);
        Map<String, Object> openId = userService.getOpenId(requestParamsNoToken);
        return AjaxJson.success().put("data",openId);
    }

}
